package com.veeder.datacollection.rs232.response.handler;

import java.util.Date;

import com.veeder.datacollection.alarm.Alarm;
import com.veeder.datacollection.alarm.Alarm.AlarmState;
import com.veeder.datacollection.alarm.AlarmId;
import com.veeder.datacollection.exception.SyntaxException;
import com.veeder.datacollection.rs232.response.AlarmList;
import com.veeder.datacollection.util.DateUtil;

public class RS113RspHandler extends CmdRspParser {

	@Override
	public AlarmList parseCoreResponse(String coreResponse) throws SyntaxException {
		AlarmList alarmsList = null;
		/*
		 * response format
		 * <SOH>i11300YYMMDDHHmma..ab..bc..cd..dAAccNNTTYYMMDDHHmm...
		 * AAccNNTTYYMMDDHHmm&&CCCC<ETX>
		 */
		try {	
			int position = 6;
			alarmsList = new AlarmList();
			alarmsList.setTlsSysDate(DateUtil.convertToDate(coreResponse.substring(position, position+=10), DateUtil.DateFormat1));
			alarmsList.setStationHdr1(coreResponse.substring(position, position+=20));
			alarmsList.setStationHdr2(coreResponse.substring(position, position+=20));
			alarmsList.setStationHdr3(coreResponse.substring(position, position+=20));
			alarmsList.setStationHdr4(coreResponse.substring(position, position+=20));
			while (position<coreResponse.length()) {
				Alarm alarm = new Alarm();
				// alarm category
				String alarmCategory = coreResponse.substring(position, position+=2);
				// set alarm type code enum
				String alarmCode = coreResponse.substring(position+=2, position+=2);
				// set Tank Number
				int deviceId = Integer.parseInt(coreResponse.substring(position, position+=2));
				AlarmId alarmId = new AlarmId(deviceId, alarmCategory, alarmCode);
				alarm.setAlarmId(alarmId);
				// use the pc time not the console time.
				// because the report time of the alarms some times are incorrect.
				position +=10;
				alarm.setReportTime(new Date());
				alarm.setState(AlarmState.Occured);
				// make a list of alarm objects
				alarmsList.addAlarm(alarm);
			}

		} catch (Exception e) {
			throw new SyntaxException(e.toString());
		}

		return alarmsList;
	}

}
